package com.xl.singletonPattern.practice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
 * 数据库连接池管理测试类
 */
public class ConnectionPoolTest {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("===数据库连接池测试===");
        //testTimeout();
        //testImmediateGet();
        testStressScenario();
    }

    /**
     * 测试超时机制
     */
    private static void testTimeout() throws InterruptedException {
        System.out.println("1.测试超时机制");
        ConnectionPool pool = ConnectionPool.getInstance();
        List<ConnectionPool.Connection> connections = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ConnectionPool.Connection connection = pool.getConnection(100);
            if (connection != null) {
                connections.add(connection);
            }
        }
        System.out.println("已获取所有连接，池状态：" + pool.getPoolStatus());
        //现在尝试获取连接，应该会超时
        Thread thread = new Thread(() -> {
            ConnectionPool.Connection connection = pool.getConnection(2000);
            if (connection == null) {
                System.out.println("✓ 超时机制工作正常：在指定时间内未获取到连接\n");
            }
        },"Timeout-Test-Thread");
        thread.start();
        thread.join();
        //释放所有连接
        for (ConnectionPool.Connection connection : connections) {
            pool.releaseConnection(connection);
        }
    }

    /**
     * 测试立即获取
     */
    private static void testImmediateGet() {
        System.out.println("2. 测试立即获取:");
        ConnectionPool pool = ConnectionPool.getInstance();
        // 测试立即获取
        ConnectionPool.Connection conn1 = pool.tryGetConnection();
        ConnectionPool.Connection conn2 = pool.tryGetConnection();
        if (conn1 != null && conn2 != null) {
            System.out.println("✓ 立即获取功能正常");
            // 使用连接
            conn1.executeQuery("SELECT 1");
            conn2.executeQuery("SELECT 2");
            // 释放连接
            pool.releaseConnection(conn1);
            pool.releaseConnection(conn2);
        }
        System.out.println("池状态: " + pool.getPoolStatus() + "\n");
    }

    /**
     * 测试压力场景
     */
    public static void testStressScenario() throws InterruptedException {
        System.out.println("3. 测试压力场景");
        ConnectionPool pool = ConnectionPool.getInstance();
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch endLatch = new CountDownLatch(8);
        // 创建8个线程，但连接池只有5个容量
        for (int i = 0; i < 8; i++) {
            final int threadId = i;
            new Thread(() -> {
                try {
                    startLatch.await(); //等待同时开始
                    ConnectionPool.Connection connection = pool.getConnection(3000);
                    if (connection != null) {
                        System.out.println("线程" + threadId + "获取连接：" + connection.getId());
                        Thread.sleep(500); //模拟业务操作
                        // 释放连接
                        pool.releaseConnection(connection);
                    } else {
                        System.out.println("线程" + threadId + "获取连接超时");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace(System.err);
                    Thread.currentThread().interrupt();
                } finally {
                    endLatch.countDown();
                }
            }, "Stress-Thread-" + i).start();
        }
        //同时启动所有线程
        startLatch.countDown();
        //等待所有线程完成
        endLatch.await();
        System.out.println("压力测试完成，最终状态: " + pool.getPoolStatus());
    }
}
